package com.cn.file;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 原子操作
 */
public abstract class ReferenceResource {

    //引用计数,>0可用， <=0不可用
    protected final AtomicLong refCount = new AtomicLong(1);

    //是否可操作
    protected volatile boolean available = true;

    //是否已清理
    protected volatile boolean cleanupOver = false;

    //第一次宕机时间
    private volatile long firstShutdownTimestamp = 0;

    public synchronized boolean hold() {
        //资源可用
        if (this.isAvailable()) {
            if (this.refCount.getAndIncrement() > 0) {
                return true;
            } else {
                this.refCount.getAndDecrement();
            }
        }
        return false;
    }

    /**
     * 参数 intervalForcibly 代表强制间隔，即两次生效的间隔至少要有这么大(不是至多!!!)
     * 第一次调用时available设置为false，设置初始时间，释放一个引用
     * 之后再调用的时候，如果refCount > 0,且超过了强制间隔，则设置为一个负数，释放一个引用
     * <p>
     * 备注：如果在intervalForcibly时间内再次shutdown 代码不会执行任何逻辑
     */
    public void shutdown(final long intervalForcibly) {
        if (this.available) {
            this.available = false;
            this.firstShutdownTimestamp = System.currentTimeMillis();
            //释放资源
            this.release();
        } else {
            if ((System.currentTimeMillis() - this.firstShutdownTimestamp) >= intervalForcibly) {
                this.refCount.set(-1000 - this.getRefCount());
                this.release();
            }
        }
    }

    /**
     * 和hold函数搭配
     * 释放一个引用，计数-1
     * 若计数 <=0，则调用cleanup，子类实现
     */
    public void release() {
        long value = this.refCount.decrementAndGet();
        if (value > 0) {
            return;
        }
        synchronized (this) {
            this.cleanupOver = this.cleanup(value);
        }
    }


    public boolean isAvailable() {
        return this.available;
    }

    public long getRefCount() {
        return this.refCount.get();
    }

    public abstract boolean cleanup(final long currentRef);

    public boolean isCleanupOver() {
        return this.refCount.get() <= 0 && this.cleanupOver;
    }

}
